package com.nosql.db.core.storage;

import com.nosql.db.core.modul.Document;

import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.LongAdder;

public class MemTable {
    private final ConcurrentSkipListMap<String, Document> table = new ConcurrentSkipListMap<>();
    private final LongAdder size = new LongAdder();
    private final LongAdder estimatedSize = new LongAdder();
    public void put(Document doc) {
        // 如果是墓碑文档，直接覆盖
        if (doc.isTombstone()) {
            table.put(doc.getId(), doc);
            return;
        }

        // 检查是否已有墓碑
        Document existing = table.get(doc.getId());
        if (existing != null && existing.isTombstone()) {
            // 保留墓碑，不覆盖
            return;
        }

        // 正常插入新文档
        table.put(doc.getId(), doc);
        System.out.println("[MemTable] 插入文档: " + doc.getId());
        estimatedSize.add(doc.toString().getBytes(StandardCharsets.UTF_8).length);
    }

    public Document get(String id) {
        return table.get(id);
    }

    public void delete(String id) {
        // 获取原始文档（需知道集合名称）
        System.out.println("[MemTable] 删除文档: " + id);
        Document original = table.get(id);
        if (original != null) {
            System.out.println("[MemTable] 原始文档存在，创建墓碑");
            // 创建墓碑文档替代原文档
            Document tombstone = new Document(original.getCollection(), new HashMap<>());
            tombstone.setId(id);
            tombstone.markAsTombstone();
            tombstone.setTimestamp(System.currentTimeMillis());
            System.out.println("[MemTable] 替换后文档类型: " +
                    (tombstone.isTombstone() ? "TOMBSTONE" : "DOCUMENT"));
            table.put(id, tombstone); // 关键：用墓碑覆盖
            // 更新大小估算
            estimatedSize.add(tombstone.toString().getBytes().length -
                    original.toString().getBytes().length);
        }
    }
    public boolean isEmpty() {
        return table.isEmpty();
    }

    public Collection<Document> values() {
        return table.values();
    }

    public void clear() {
        table.clear();
        size.reset();
    }
    public long estimateSize() {
        return this.estimatedSize.sum();
    }

}
